package com.vf.admin.client.controller.oldPay.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.*;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.pay.ApiAliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.vf.admin.common.Constants.dingdan_status_dfk;
import static com.vf.admin.common.Constants.dingdan_zhiFuLeiXing_zfb;

/**
 * 支付宝支付
 *
 * @author anxiang
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/api/alipay")
public class ApiAlipayController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    AppUserService appUserService;
    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    ApiAlipayService apiAlipayService;
    @Autowired
    AlipayConfigsService alipayConfigsService;
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;
    @Autowired
    private AppSetupService appSetupService;
    @Autowired
    private AgentUserService agentUserService;
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    AppPrivilegeService appPrivilegeService;
    @Autowired
    AppCzMoneyService appCzMoneyService;
    @Autowired
    AppPaySetupService appPaySetupService;


    /**
     * 钻石充值
     *
     * @param request
     * @param money   充值金额
     * @return
     */
    @RequestMapping(value = "/diamondRecharge", method = RequestMethod.POST)
    @ResponseBody
    public Result diamondRechargeAlipay(HttpServletRequest request, Double money, Integer id) {
        try {
            AppSetup setup = appSetupService.get();
            if (setup.getOpenRecharge() == 0) {
                return this.errorJSON(setup.getRechargeTip());
            }

            if (money == null || money <= 0) {
                return this.errorJSON("请你输入充值金额!");
            }
            //下单人信息
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            AppCzMoney appCzMoney = appCzMoneyService.get(id);
            String orderString = apiAlipayService.diamondRechargeAlipay(user, appCzMoney);
            if (orderString == null || orderString.trim().length() <= 0) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(orderString);
        } catch (Exception e) {
            logger.error("支付宝充值异常:", e);
            return this.errorJSON("服务器繁忙，请您稍后重试!");
        }
    }

    /**
     * h5钻石充值
     *
     * @param request
     * @param productId 产品ID
     * @return
     */
    @RequestMapping(value = "/diamondRechargeByWeb", method = RequestMethod.POST)
    @ResponseBody
    public Result diamondRechargeByWeb(HttpServletRequest request, Integer productId) {
        try {
            AppSetup setup = appSetupService.get();
            if (setup.getOpenRecharge() == 0) {
                return this.errorJSON(setup.getRechargeTip());
            }
            //下单人信息
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            AppCzMoney appCzMoney = appCzMoneyService.get(productId);
            String orderString = apiAlipayService.diamondRechargeAlipayByWeb(user, appCzMoney);
            if (orderString == null || orderString.trim().length() <= 0) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(orderString);
        } catch (Exception e) {
            logger.error("支付宝充值异常:", e);
            return this.errorJSON("服务器繁忙，请您稍后重试!");
        }
    }


    /**
     * 支付宝回掉接口
     *
     * @param request
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/NotifyUrl/{from}/{appIdStr}", method = RequestMethod.POST)
    @ResponseBody
    public String NotifyUrl(HttpServletRequest request, @PathVariable("from") String from, @PathVariable("appIdStr") String appIdStr) throws UnsupportedEncodingException {
        logger.info("appIdStr:" + appIdStr);
        logger.info("from:" + from);
        AppPaySetup appPaySetup = appPaySetupService.getByAppIdStr(appIdStr);

        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, appPaySetup.getAlipayPublicKey(), AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);

        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("——————商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            if ("TRADE_SUCCESS".equals(trade_status)) {
                /**
                 * 返回的状态是success，接下来可以：更改订单支付成功状态，设置支付信息，等等业务处理……
                 */
                if (from.equalsIgnoreCase("VIP")) {
                    vipOrderService.successCall(out_trade_no);
                } else if (from.equalsIgnoreCase("RECHARGE")) {
                    try {
                        //根据订单号、支付状态、支付方式获取预订单
                        AppOrder topup = appOrderService.getByOrdernum(out_trade_no, dingdan_zhiFuLeiXing_zfb, dingdan_status_dfk);
                        //判断预订单是否存在
                        if (!StringUtils.isEmpty(topup)) {
                            AppUser user = appUserService.get(topup.getUserid());
                            //存在则更改预订单支付状态
                            appOrderService.updateStastusYzf(out_trade_no, 1);
                            BigDecimal getDiamond = topup.getNum();
                            //添加用户钻石金额
                            appUserService.updateZuanShi(user.getId(), getDiamond);
                            //增加用户累积充值金额
                            appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                            //添加钻石明细
                            appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                            //添加充值明细
                            appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no,topup.getMobileSpec());
                            //完成充值任务
                            appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                            //如果有上级发放用户充值提成
                            addAward(topup);
                            //升级贵族
                            appPrivilegeService.isUpLevel(user);
                            logger.info("支付宝回调成功，充值入账成功");
                        }
                        return "success";
                    } catch (Exception e) {
                        logger.info("---------------异常——————————————");
                    }
                }
            } else {
                /**
                 *  fail 的业务处理：……
                 */
                logger.info("fail");
                return "success";
            }
        }
        return "success";
    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(HttpServletRequest request) throws UnsupportedEncodingException {
        if (true) {
            // 商户订单号
            String out_trade_no = "1000001520339676";
            // 支付宝交易号
            String trade_no = "2000001069630843";
            try {
                //根据订单号、支付状态、支付方式获取预订单
                AppOrder topup = appOrderService.getByOrdernum(out_trade_no, dingdan_zhiFuLeiXing_zfb, dingdan_status_dfk);

                //判断预订单是否存在
                if (!StringUtils.isEmpty(topup)) {
                    AppUser user = appUserService.get(topup.getUserid());
                    //存在则更改预订单支付状态
                    appOrderService.updateStastusYzf(out_trade_no, 1);

                    BigDecimal getDiamond = topup.getNum();

                    //添加用户钻石金额
                    appUserService.updateZuanShi(user.getId(), getDiamond);
                    //增加用户累积充值金额
                    appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                    //添加钻石明细
                    appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                    //添加充值明细
                    appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no,topup.getMobileSpec());
                    //完成充值任务
                    appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                    //如果有上级发放用户充值提成
                    addAward(topup);
                    //升级贵族
                    appPrivilegeService.isUpLevel(user);
                    logger.info("支付宝回调成功，充值入账成功");
                }
                return "success";
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("---------------异常——————————————");
            }
        }
        return "success";
    }


    /**
     * 邀请用户充值增加父级提成
     *
     * @param order
     */
    public void addAward(AppOrder order) {
        AppInvitationRecord record = appInvitationRecordService.getShangji(order.getUserid());
        if (record != null) {
            AppSetup appSetup = appSetupService.get();
            BigDecimal divide = order.getNum().multiply(appSetup.getRechargeInvite()).setScale(2, BigDecimal.ROUND_HALF_UP);
            appUserService.addDiamonds(record.getPuserid(), divide, "邀请用户充值提成");
        }
    }

    /*************************************新支付**************************************

     /**
     * 业务说明：多收款账号，根据账号权重进行收款
     *
     * @param request
     * @param productId 产品ID
     * @param type
     * @return
     * @auth zxw
     * @date 2023/06/19 14:24
     */
    @RequestMapping(value = "/otherAliPay", method = RequestMethod.POST)
    @ResponseBody
    public Result otherAliPay(HttpServletRequest request, Integer productId, String type) {
        try {
            AppSetup setup = appSetupService.get();
            if (setup.getOpenRecharge() == 0) {
                return this.errorJSON(setup.getRechargeTip());
            }
            //下单人信息
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            AppCzMoney appCzMoney = appCzMoneyService.get(productId);
            String orderString = alipayConfigsService.otherAlipayWeb(user, appCzMoney);
            if (orderString == null || orderString.trim().length() <= 0) {
                return this.errorJSON("充值失败，请您重新充值!");
            }
            return this.sucessJSON(orderString);
        } catch (Exception e) {
            logger.error("支付宝充值异常:", e);
            return this.errorJSON("服务器繁忙，请您稍后重试!");
        }
    }

    /**
     * 权重测试
     */
    @RequestMapping(value = "/weight", method = RequestMethod.GET)
    @ResponseBody
    public Result otherAliPay() {
        AlipayConfigs playInfo = alipayConfigsService.getWeightPlayInfo();
        return this.sucessJSON(playInfo);
    }

    /**
     * 支付宝回调接口
     *
     * @param request
     * @param appIdStr appId
     * @return
     */
    @RequestMapping(value = "/AiliNotifyUrl/{appIdStr}", method = RequestMethod.POST)
    @ResponseBody
    public String AiliNotifyUrl(HttpServletRequest request, @PathVariable("appIdStr") String appIdStr) throws UnsupportedEncodingException {
        //获取对应详细信息
        AlipayConfigs appIdInfo = alipayConfigsService.getAppIdInfo(appIdStr);
        //通过appId获取对应账号信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, appIdInfo.getAlipayPublicKey(), AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            logger.info("验证公钥时出现异常");
        } // 调用SDK验证签名
        logger.info("验证签名结果" + signVerified);
        //对应数据库操作
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            logger.info("-----------商户订单号" + out_trade_no);
            logger.info("-----------支付宝交易号" + trade_no);
            logger.info("-----------交易状态" + trade_status);
            //订单支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {

                //根据订单号、支付状态、支付方式获取预订单
                AppOrder topup = appOrderService.getByOrdernum(out_trade_no, dingdan_zhiFuLeiXing_zfb, dingdan_status_dfk);
                if (!StringUtils.isEmpty(topup)) {
                    AppUser user = appUserService.get(topup.getUserid());
                    //存在则更改预订单支付状态
                    appOrderService.updateStastusYzf(out_trade_no, 1);
                    BigDecimal getDiamond = topup.getNum();
                    //添加用户钻石金额
                    appUserService.updateZuanShi(user.getId(), getDiamond);
                    //增加用户累积充值金额
                    appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                    //添加钻石明细
                    appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                    //添加充值明细
                    appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no,topup.getMobileSpec());
                    //完成充值任务
                    appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                    //如果有上级发放用户充值提成
                    addAward(topup);
                    //升级贵族
                    appPrivilegeService.isUpLevel(user);
                    logger.info("支付宝回调成功，充值入账成功");
                }

            }
        }
        return "success";
    }


}
